﻿/*******************************************************
 * 
 * 作者：胡庆访
 * 创建时间：20100408
 * 说明：界面自动自成类
 * 运行环境：.NET 3.5 SP1
 * 版本号：1.0.0
 * 
 * 历史记录：
 * 创建文件 胡庆访 20100408
 * 
*******************************************************/
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using Avalon.Windows.Controls;
using AvalonDock;
using Csla;
using Itenso.Windows.Input;

using OpenExpressApp.MetaModel;
using OpenExpressApp.Module.Command;
using OpenExpressApp.Module.Library;
using OpenExpressApp.Module.Library.Security;
using OpenExpressApp.Module.WPF.Controls;
using OpenExpressApp.Module.WPF.Templete;
using OpenExpressApp.Types;
using OpenExpressApp.WPF.Command;
using OpenExpressApp.WPF.Controls;
using OpenExpressApp.WPF.Editors;
using Wpf.Controls;
using System.Windows.Automation;

namespace OpenExpressApp.Module.WPF
{
    internal class DefaultUIFactory : IUIFactory
    {
        private CommandUIGenerator _commandUI;

        public DefaultUIFactory()
        {
            this._commandUI = new CommandUIGenerator(this);
        }

        #region IUIFactory Members

        public DataGrid CreateListControl(IListObjectView view)
        {
            if (view == null) throw new ArgumentNullException("view");
            Type boType = view.EntityType;

            //使用DataGrid作为显示控件
            DataGrid dg = new SelectionDataGrid()
            {
                CanUserAddRows = false,
                AutoGenerateColumns = false,
                VerticalGridLinesBrush = new SolidColorBrush(Colors.Gray),
                HorizontalGridLinesBrush = new SolidColorBrush(Colors.Gray),
            };

            //if ((null != view.BOsPropInfo) && (AssociationOperateType.Selected == view.BOsPropInfo.AssociationAttribute.AssociationOperateType))
            //    dg.SetValue(SelectedDataAttached.IsCheckedProperty, true);

            //一些默认属性
            BusinessObjectInfo boInfo = ApplicationModel.GetBusinessObjectInfo(boType);
            if (0 != boInfo.BusinessObjectAttribute.Height)
            {
                dg.Height = (int)boInfo.BusinessObjectAttribute.Height;
            }

            #region 生成每一列

            foreach (var item in boInfo.BOPropertyInfos)
            {
                bool generate;

                if (view.RegionType == RegionType.LookupList)
                {
                    generate = item.ShowInLookup;
                }
                else
                {
                    generate = item.ShowInList;
                }

                if (generate)
                {
                    DataGridColumn c = item.CreateDefaultGridColumn(view);
                    if (item.MinWidth != 0)
                    {
                        c.Width = item.MinWidth;
                    }
                    dg.Columns.Add(c);
                }
            }

            #endregion

            return dg;
        }

        public MultiObjectTreeView CreateTreeListControl(IListObjectView view)
        {
            if (view == null) throw new ArgumentNullException("view");
            Type boType = view.EntityType;

            //使用MultiObjectTreeView作为TreeListControl
            var treeListControl = new MultiObjectTreeView();
            treeListControl.SelectNodesOnRightClick = true;

            //都按懒加载关系处理
            //if (ApplicationModel.GetBusinessObjectInfo(boType).LazyTreeNodeRelation) 
            //    otv.LazyTreeNodeRelation = true;

            //装载多个对象的属性
            BusinessObjectInfo boInfo = ApplicationModel.GetBusinessObjectInfo(boType);
            var propInfos = boInfo.BOPropertyInfos.ToList();

            #region 把模型下的需要一同显示在树中的子模型的列，加入List中

            var childInfo = boInfo;
            while (null != childInfo.TreeChildPropertyInfo)
            {
                //子模型的
                childInfo = childInfo.TreeChildBoInfo;

                //加入还没有存在的
                foreach (var item in childInfo.BOPropertyInfos)
                {
                    bool notExists = propInfos.All(propInfo => propInfo.Name != item.Name);
                    if (notExists)
                    {
                        propInfos.Add(item);
                    }
                }
            }

            #endregion

            #region 使用list里面的属性生成每一列

            foreach (var item in propInfos)
            {
                bool generate;

                if (view.RegionType == RegionType.LookupList)
                {
                    generate = item.ShowInLookup;
                }
                else
                {
                    generate = item.ShowInList;
                }
                if (generate)
                {
                    GridViewColumn c = item.CreateDefaultTreeColumn(view);
                    if (item.MinWidth != 0)
                    {
                        c.Width = item.MinWidth;
                    }
                    ViewLayoutManager.SetEnabled(treeListControl.Tree, true);
                    RangeColumn.SetMinWidth(c, c.Width);
                    treeListControl.Tree.Columns.Add(c);
                }
            }

            #endregion

            return treeListControl;
        }

        public FrameworkElement CreateDetailView(DetailObjectView detailView, int colCount)
        {
            if (detailView == null) throw new ArgumentNullException("detailView");
            Type boType = detailView.BOType;

            DockPanel detailPanel = new DockPanel();

            AutoGrid detailGrid = new AutoGrid();
            detailGrid.SetValue(DockPanel.DockProperty, Dock.Top);
            //支持UI Test
            detailGrid.SetValue(AutomationProperties.AutomationIdProperty, "detail:"+ ApplicationModel.GetBusinessObjectInfo(detailView.BOType).Id);

            //一般加四列，ConditionQuery/NavigateQuery加两列
            for (int i = 0; i < colCount; i++)
            {
                detailGrid.ColumnDefinitions.Add(new ColumnDefinition() { Width = GridLength.Auto });
                detailGrid.ColumnDefinitions.Add(new ColumnDefinition());
            }

            #region 加入所有标记了ShowInDetail的属性

            var typeInfo = ApplicationModel.GetBusinessObjectInfo(boType);
            foreach (var p in typeInfo.BOPropertyInfos)
            {
                if (p.ShowInDetail)
                {
                    var editor = PropertyEditorsFactory.CreateDefaultEditor(p.EditorName, detailView, p);
                    editor.EnsureControlsCreated();
                    detailGrid.Children.Add(editor.LabelControl);
                    detailGrid.Children.Add(editor.Control);
                    //支持UI Test
                    editor.Control.SetValue(AutomationProperties.AutomationIdProperty, "propertyEditor:" + p.Label);
                }
            }

            #endregion

            //添加AutoGrid到panel中
            detailPanel.Children.Add(detailGrid);

            //生成子UIElement
            var childGenerator = new ChildUIGenerator(this, detailView);
            UIElement child = childGenerator.GenerateControl(detailGrid);
            if (null != child)
            {
                detailPanel.Children.Add(child);
            }
            else
            {
                detailPanel.Children.Add(new Label());
            }

            return detailPanel;
        }

        public void CreateMainToolBar(ToolBar mainToolbar, Type boType, WPFObjectView view, ModuleType moduleType)
        {
            if (mainToolbar == null) throw new ArgumentNullException("mainToolbar");
            if (boType == null) throw new ArgumentNullException("boType");
            if (view == null) throw new ArgumentNullException("view");

            view.ToolBar = mainToolbar;

            //找到对应这个toolbar的所有command
            BoInfoOperationList boInfoOperationnList = BoInfoOperationList.GetList(ApplicationModel.GetBusinessObjectInfo(boType));

            this._commandUI.CreateCommandsForToolBar(mainToolbar, boType, view, boInfoOperationnList);
        }

        public void CreateChildToolBar(WPFObjectView view, Type boType)
        {
            if (boType == null) throw new ArgumentNullException("boType");
            if (view == null) throw new ArgumentNullException("view");

            var childToolbar = view.ToolBar;
            if (childToolbar == null) throw new ArgumentNullException("mainToolbar");

            //找到对应这个toolbar的所有command
            BoInfoOperationList boInfoOperationnList = BoInfoOperationList.GetList(ApplicationModel.GetBusinessObjectInfo(boType));

            this._commandUI.CreateCommandsForToolBar(childToolbar, boType, view, boInfoOperationnList);

            //生成LookupAttribute.UseSelectAddCommand
            foreach (var item in ApplicationModel.GetBusinessObjectInfo(boType).BOPropertyInfos)
            {
                if ((null != item.LookupAttribute) && (item.LookupAttribute.UseSelectAddCommand))
                {
                    CommandAdapter command = CommandRepository.NewCommand(CommandNames.LookupSelectAdd);
                    string label = item.Label;
                    if (String.IsNullOrEmpty(label))
                        label = ApplicationModel.GetBusinessObjectInfo(item.LookupAttribute.LookupType).Label;
                    command.Description.Text = String.Format("选择{0}", label);
                    (command.CoreCommand as ISelectAddCommandParams).BoType = item.LookupAttribute.LookupType;
                    var btn = new Button();
                    btn.CommandParameter = view;
                    ButtonCommand.SetCommand(btn, command);
                    childToolbar.Items.Add(btn);
                }
            }
            //添加弹出子窗体按钮
            this._commandUI.CreatePopChildCommandsForToolBar(childToolbar.Items, boType, view);
        }

        #endregion
    }
}
